package com.lechuang.dashu.view.activity.own;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ali.auth.third.core.model.Session;
import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.alibaba.baichuan.android.trade.adapter.login.AlibcLogin;
import com.alibaba.baichuan.android.trade.callback.AlibcLoginCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.AlibcTaokeParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcBasePage;
import com.alibaba.baichuan.android.trade.page.AlibcMyCartsPage;
import com.alibaba.baichuan.android.trade.page.AlibcMyOrdersPage;
import com.bumptech.glide.Glide;
import com.lechuang.dashu.R;
import com.lechuang.dashu.base.Constants;
import com.lechuang.dashu.base.MyApplication;
import com.lechuang.dashu.model.DemoTradeCallback;
import com.lechuang.dashu.model.LeCommon;
import com.lechuang.dashu.model.LocalSession;
import com.lechuang.dashu.model.bean.OwnUserInfoBean;
import com.lechuang.dashu.model.bean.UpdataInfoBean;
import com.lechuang.dashu.presenter.CommonAdapter;
import com.lechuang.dashu.presenter.net.Netword;
import com.lechuang.dashu.presenter.net.ResultBack;
import com.lechuang.dashu.presenter.net.netApi.CommenApi;
import com.lechuang.dashu.presenter.net.netApi.OwnApi;
import com.lechuang.dashu.utils.Utils;
import com.lechuang.dashu.view.activity.sun.SunActivity;
import com.lechuang.dashu.view.activity.tipoff.TipOffActivity;
import com.lechuang.dashu.view.activity.ui.LoginActivity;
import com.lechuang.dashu.view.defineView.MGridView;
import com.lechuang.dashu.view.defineView.ViewHolder;
import com.lechuang.dashu.view.defineView.XCRoundImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 作者：li on 2017/9/21 17:46
 * 邮箱：961567115@qq.com
 * 修改备注:
 */
public class OwnFragment extends Fragment implements AdapterView.OnItemClickListener {

    @BindView(R.id.iv_set)
    ImageView ivSet;
    @BindView(R.id.iv_news)
    ImageView ivNews;
    @BindView(R.id.iv_headImg)
    XCRoundImageView iv_headImg;
    @BindView(R.id.tv_login_or_register)
    TextView tvLoginOrRegister;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    //    @BindView(R.id.line_vip)
//    LinearLayout lineVip;
    @BindView(R.id.tv_jifen)
    TextView tvJifen;
    @BindView(R.id.gv_state)
    MGridView gvState;
    @BindView(R.id.ll_myincom)
    TextView llMyincom;
    @BindView(R.id.ll_jifengtixian)
    TextView ll_jifengtixian;
    @BindView(R.id.ll_task)
    TextView llTask;
    @BindView(R.id.tv_cart)
    TextView tv_cart;
    @BindView(R.id.ll_myagent)
    TextView llMyagent;
    @BindView(R.id.ll_get_fanli)
    LinearLayout llGetFanli;
    @BindView(R.id.ll_go_share)
    LinearLayout llGoShare;
    @BindView(R.id.tv_item_number)
    TextView tvItemNumber;
    @BindView(R.id.tv_my_item)
    TextView tvMyItem;
    private String str[] = {"待付款", "待发货", "待收货", "售后", "全部订单"};
    private int images[] = {R.drawable.wode_daifukuan, R.drawable.wode_daifahuo, R.drawable.wode_daishouhuo,
            R.drawable.wode_shouhou, R.drawable.wode_quanbudingdam};

    private LocalSession mSession;
    //打开页面的方法
    private AlibcShowParams alibcShowParams = new AlibcShowParams(OpenType.Native, false);
    private Map exParams = new HashMap<>();

    //保存用户登录信息的sp
    private SharedPreferences se;

    private int signedStatus;
    private Unbinder unbinder;
    private LocalSession session;
    private String url;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_own, container, false);
        unbinder = ButterKnife.bind(this, v);
        initView();
        return v;
    }

    /**
     * @author li
     * 邮箱：961567115@qq.com
     * @time 2017/9/22  20:01
     * @describe 初始化下边的淘宝订单信息
     */
    private void initView() {
        //保存用户登录信息的sp
        se = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mSession = LocalSession.get(getActivity());
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < images.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("image", images[i]);
            map.put("name", str[i]);
            list.add(map);
        }
        gvState.setAdapter(new CommonAdapter<Map<String, Object>>(getActivity(), list, R.layout.home_kinds_item) {
            @Override
            public void setData(ViewHolder viewHolder, Object item) {
                viewHolder.getView(R.id.iv_kinds_img).setVisibility(View.GONE);
                viewHolder.getView(R.id.iv_own).setVisibility(View.VISIBLE);
                HashMap<String, Object> map = (HashMap<String, Object>) item;
                String name = (String) map.get("name");
                int img = (int) map.get("image");
                viewHolder.setText(R.id.tv_kinds_name, name);
                viewHolder.setImageResource(R.id.iv_own, img);
            }
        });
        gvState.setOnItemClickListener(this);
        exParams.put("isv_code", "appisvcode");
        exParams.put("alibaba", "阿里巴巴");//自定义参数部分，可任意增删改
    }

    @Override
    public void onStart() {
        super.onStart();
        if (se.getBoolean(LeCommon.KEY_HAS_LOGIN, false))
            getData();
        //是否登录
        mSession.setLogin(se.getBoolean("isLogin", false));
        //id
        mSession.setId(se.getString("id", ""));
        if (se.getBoolean("isLogin", false)) {

            //tvVip.setVisibility(View.VISIBLE);
            if (!se.getString("photo", "").equals("")) {
                Glide.with(MyApplication.getInstance()).load(se.getString("photo", "")).into(iv_headImg);
            }
            //没有昵称时展示手机号
            String nick = se.getString("nickName", se.getString("phone", "----"));
            tvLoginOrRegister.setText(nick.length() > 9 ? nick.substring(0, 7) + "..." : nick);
            tvLoginOrRegister.setEnabled(false);
        } else {
            tvJifen.setText("0.00");
            tvLoginOrRegister.setText("登录/注册");
            iv_headImg.setImageResource(R.drawable.pic_morentouxiang);
            //tvVip.findViewById(R.id.tv_vip).setVisibility(View.GONE);//vip
            tvLoginOrRegister.setEnabled(true);
            llGetFanli.setVisibility(View.VISIBLE);
            llGoShare.setVisibility(View.GONE);
        }

    }

    private void getData() {
        Netword.getInstance().getApi(OwnApi.class)
                .userInfo()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<OwnUserInfoBean>(getActivity()) {
                    @Override
                    public void successed(OwnUserInfoBean result) {
                        if (result.vipGradeName != null && !result.vipGradeName.equals("")) {
                            tvVip.setText(result.vipGradeName);
                        } else {
                            tvVip.setText("了解会员");
                        }
                        tvJifen.setText(result.withdrawIntegral);
                        tvItemNumber.setText(result.agencyNum + "人");
                        signedStatus = result.signedStatus;
                        se.edit().putInt("isAgencyStatus", result.isAgencyStatus).apply();

                        if (result.isAgencyStatus == 1) {
                            llGetFanli.setVisibility(View.GONE);
                            llGoShare.setVisibility(View.VISIBLE);
                        } else {
                            llGetFanli.setVisibility(View.VISIBLE);
                            llGoShare.setVisibility(View.GONE);
                        }
                    }
                });
    }

    @OnClick({R.id.iv_set, R.id.tv_tuiguang, R.id.iv_news, R.id.tv_taobao, R.id.ll_get_fanli, R.id.ll_jifengtixian, R.id.tv_cart,
            R.id.tv_login_or_register, R.id.tv_help, R.id.ll_myincom, R.id.ll_task, R.id.tv_baoliao,
            R.id.ll_myagent, R.id.tv_vip, R.id.tv_shaidan, R.id.tv_my_item, R.id.tv_item_number})
    public void onViewClicked(View view) {
        if (mSession.isLogin()) {
            switch (view.getId()) {
                case R.id.tv_cart: //购物车
                    AlibcBasePage alibcBasePage = new AlibcMyCartsPage();
                    AlibcTaokeParams taokeParams = new AlibcTaokeParams(Constants.PID, "", "");
                    AlibcTrade.show(getActivity(), alibcBasePage, alibcShowParams, taokeParams, exParams, new DemoTradeCallback());
                    break;
                case R.id.ll_jifengtixian:
                    startActivity(new Intent(getActivity(), JinfenReflectActivity.class));
                    break;
                case R.id.tv_baoliao:   //爆料
                    startActivity(new Intent(getActivity(), TipOffActivity.class));
                    break;
                case R.id.tv_tuiguang:   //开始推广
                case R.id.ll_myagent:  //分享
                    startActivity(new Intent(getActivity(), ShareMoneyActivity.class));
                    //  share();
                    break;
                case R.id.tv_my_item:   //英雄榜
                    startActivity(new Intent(getActivity(), HeroActivity.class));
                    break;
                case R.id.tv_item_number:   //团队人数
                    startActivity(new Intent(getActivity(), MyTeamActivity.class));
                    break;
                case R.id.tv_taobao:
                    if (Utils.isNetworkAvailable(getActivity())) {
                        final AlibcLogin alibcLogin = AlibcLogin.getInstance();
                        alibcLogin.showLogin(getActivity(), new AlibcLoginCallback() {
                            @Override
                            public void onSuccess() {
                                Session taobao = alibcLogin.getSession();
                                //mSession.setLogin(true);
                                //mSession.setImge(taobao.avatarUrl);
                                //mSession.setName(taobao.nick);
                                //mSession.setAccountNumber(taobao.nick);
                                updateInfoTaobao(taobao.nick);
                                //finish();
                            }

                            @Override
                            public void onFailure(int i, String s) {
                                Utils.show(getActivity(), s);

                            }
                        });
                    } else {
                        Utils.show(getActivity(), getString(R.string.net_error1));
                    }
                    break;
                case R.id.tv_help:   //帮助中心
                    startActivity(new Intent(getActivity(), HelpCenterActivity.class));
                    break;
                case R.id.tv_shaidan:   //晒单
                    startActivity(new Intent(getActivity(), SunActivity.class));
                    break;
                case R.id.iv_set://设置
                    startActivity(new Intent(getActivity(), SetActivity.class));
                    break;
                case R.id.iv_news://消息
                    startActivity(new Intent(getActivity(), NewsCenterActivity.class));
                    break;
                case R.id.tv_vip://vip
                    startActivity(new Intent(getActivity(), VipActivity.class));
                    break;
                case R.id.tv_login_or_register://注册。登录
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    break;
                case R.id.ll_myincom://账户明细
                    startActivity(new Intent(getActivity(), MyIncomeActivity.class));
                    break;
                case R.id.ll_task://任务中心
                    startActivity(new Intent(getActivity(), TaskCenterActivity.class));
                    break;
                case R.id.ll_get_fanli:
                    if (se.getInt("isAgencyStatus", 0) == 1) {
                        startActivity(new Intent(getActivity(), MyTeamActivity.class));
                    } else {
                        startActivity(new Intent(getActivity(), ApplyAgentActivity.class));
                    }
                    break;
            }
        } else {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }

    }

   /* */
    /**
     * 用户分享
     *//*
    private void share() {
        session = LocalSession.get(getActivity());
        //!=1 不是代理       =1 是代理
        if (session.getIsAgencyStatus() == 1) {                                    //代理分享
            url = QUrl.activityShare + "?i=" + session.getId();
            new ShareModel().gotoShareText(getActivity(), "玩转" + getResources().getString(R.string.app_name) + "代理分享:" + "\n" + url);
        } else {                                                                 //用户分享
            Netword.getInstance().getApi(OwnApi.class)
                    .getShare(1)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ResultBack<ShareBean>(getActivity()) {
                        @Override
                        public void successed(ShareBean result) {
                            if(result==null){
                                return;
                            }
                          url=result.image;
                            new ShareModel().gotoShareText(getActivity(), "玩转" + getResources().getString(R.string.app_name) + "用户分享:" + "\n" + url);
                        }
                    });
        }
    }*/

    int orderType = 0;


    /**
     * 淘宝更改
     *
     * @param nick
     */
    private void updateInfoTaobao(final String nick) {
        Map<String, String> map = new HashMap<>();
        map.put("taobaoNumber", nick);
        Netword.getInstance().getApi(CommenApi.class)
                .updataInfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<UpdataInfoBean>(getActivity()) {
                    @Override
                    public void successed(UpdataInfoBean result) {
                        se.edit().putString("taobaoNumber", nick).commit();
                    }
                });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mSession.isLogin()) {
            switch (images[position]) {
                case R.drawable.wode_daifukuan://代付款
                    orderType = 1;
                    break;
                case R.drawable.wode_daifahuo://待发货
                    orderType = 2;
                    break;
                case R.drawable.wode_daishouhuo://待收货
                    orderType = 3;
                    break;
                case R.drawable.wode_shouhou://售后
                    orderType = 4;
                    break;
                case R.drawable.wode_quanbudingdam://全部订单
                    orderType = 0;
                    break;

            }
            AlibcBasePage alibcBasePage = new AlibcMyOrdersPage(orderType, true);
            AlibcTrade.show(getActivity(), alibcBasePage, alibcShowParams, null, exParams, new DemoTradeCallback());
        } else {

            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AlibcTradeSDK.destory();
        unbinder.unbind();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
           /* if (data.getIntExtra("sign", 0) == 1) {
                tv_sign.setText("已签到");
            } else {
                tv_sign.setText("签到");
            }*/
        }
    }
}